import React from 'react';
import { Card, Row, Col, DatePicker, Select, Statistic, Table, Tabs } from 'antd';
import * as echarts from 'echarts';
import { SettingOutlined, AreaChartOutlined, AlertOutlined } from '@ant-design/icons';

const { RangePicker } = DatePicker;

export default function Main() {
  const [rangeType, setRangeType] = React.useState(1); // 1: 一天, 2: 一周, 3: 一月, 4: 自选
  const [metric, setMetric] = React.useState('onlineRate');
  const [dateRange, setDateRange] = React.useState(null);
  const chartRef = React.useRef(null);
  const chartInstanceRef = React.useRef(null);
  // 机器排名（按销售额）
  const machineRanking = React.useMemo(() => ([
    { name: '上海徐汇区-自动售货机A1', amount: 20987 },
    { name: '北京朝阳区-自动售货机B3', amount: 19872 },
    { name: '广州天河区-自动售货机C2', amount: 17653 },
    { name: '深圳南山区-自动售货机D5', amount: 15430 },
    { name: '杭州西湖区-自动售货机E7', amount: 13210 },
    { name: '南京鼓楼区-自动售货机F9', amount: 12105 },
    { name: '成都高新区-自动售货机G4', amount: 11022 },
    { name: '武汉武昌区-自动售货机H6', amount: 10488 },
    { name: '苏州工业园-自动售货机I2', amount: 9876 },
    { name: '重庆渝北区-自动售货机J8', amount: 9231 },
  ]), []);
  // 用户排名（按消费额）
  const userRanking = React.useMemo(() => ([
    { name: '张三', amount: 18230 },
    { name: '李四', amount: 17020 },
    { name: '王五', amount: 16580 },
    { name: '赵六', amount: 15010 },
    { name: '钱七', amount: 14200 },
    { name: '孙八', amount: 13860 },
    { name: '周九', amount: 13215 },
    { name: '吴十', amount: 12008 },
    { name: '郑十一', amount: 10892 },
    { name: '王十二', amount: 10015 },
  ]), []);
  // 产品排名（按销售额）
  const productRanking = React.useMemo(() => ([
    { name: '冰露矿泉水500ml', amount: 29870 },
    { name: '可口可乐330ml', amount: 27650 },
    { name: '统一冰红茶500ml', amount: 24320 },
    { name: '百事可乐330ml', amount: 22110 },
    { name: '康师傅绿茶500ml', amount: 20540 },
    { name: '乐事薯片原味', amount: 18760 },
    { name: '士力架巧克力', amount: 17680 },
    { name: '脉动维生素饮料', amount: 16490 },
    { name: '农夫山泉茶π', amount: 15330 },
    { name: '雪碧330ml', amount: 14220 },
  ]), []);

  const rankingColumns = [
    {
      title: '排名',
      dataIndex: 'rank',
      width: 90,
      render: (_, __, index) => {
        const colors = ['#fadb14', '#d9d9d9', '#fa8c16'];
        const color = colors[index] || '#1890ff22';
        return (
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <div style={{ width: 24, height: 24, borderRadius: '50%', background: color, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12 }}>
              {index + 1}
            </div>
          </div>
        );
      },
    },
    { title: '名称', dataIndex: 'name' },
    {
      title: '销售额',
      dataIndex: 'amount',
      align: 'right',
      width: 160,
      render: (v) => `￥ ${Number(v).toLocaleString('zh-CN')}`,
    },
  ];

  const renderRankingTable = (data) => (
    <Table
      size="small"
      pagination={false}
      rowKey={(r) => r.name}
      dataSource={data}
      columns={rankingColumns}
    />
  );

  // 初始化图表，仅运行一次
  React.useEffect(() => {
    const dom = chartRef.current;
    if (!dom) return;
    const instance = echarts.init(dom);
    chartInstanceRef.current = instance;
    const handleResize = () => instance.resize();
    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
      instance.dispose();
      chartInstanceRef.current = null;
    };
  }, []);

  // 更新图表数据/样式
  React.useEffect(() => {
    const instance = chartInstanceRef.current;
    if (!instance) return;
    const { labels, data } = generateSeries(rangeType, metric, dateRange);
    const color = metric === 'onlineRate' ? '#1890ff' : metric === 'sales' ? '#ff6b72' : '#00d6af';
    const option = {
      grid: { left: 40, right: 20, top: 30, bottom: 30 },
      tooltip: { trigger: 'axis' },
      xAxis: { type: 'category', data: labels, boundaryGap: false, axisLine: { lineStyle: { color: '#ddd' } } },
      yAxis: { type: 'value', axisLine: { lineStyle: { color: '#ddd' } } },
      series: [
        {
          type: 'line',
          smooth: true,
          data,
          symbol: 'circle',
          symbolSize: 6,
          lineStyle: { color },
          itemStyle: { color },
          areaStyle: { color, opacity: 0.12 },
        },
      ],
    };
    instance.setOption(option);
  }, [rangeType, metric, dateRange]);

  const topCard = (color, icon, title, center, suffix, bottoms) => (
    <Card variant="borderless" styles={{ body: { padding: 15 } }}>
      <div style={{ display: 'flex', alignItems: 'center' }}>
        <div style={{ width: 36, height: 36, backgroundColor: color, borderRadius: '50%', display: 'flex', justifyContent: 'center', alignItems: 'center', marginRight: 10 }}>
          {icon}
        </div>
        <div style={{ fontSize: 16, height: 36, lineHeight: '36px', color: '#7b7b7b', fontWeight: 'bold' }}>{title}</div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', marginTop: 5 }}>
        <div style={{ fontSize: 16, height: 30, lineHeight: '30px' }}>
          <span style={{ fontSize: 30, fontWeight: 'bold', color: color }}>{center}</span>
          {suffix && <span style={{ fontSize: 14, color: '#999', marginLeft: 4 }}>{suffix}</span>}
        </div>
      </div>
      {bottoms?.length ? (
        <div style={{ display: 'flex', width: '100%', alignItems: 'center', justifyContent: 'center', marginTop: 15 }}>
          {bottoms.map((b, idx) => (
            <div key={idx} style={{ width: `${100 / bottoms.length}%`, textAlign: 'center' }}>
              <div style={{ fontSize: 12, color: b.color, fontWeight: 'bold' }}>{b.value}</div>
              <div style={{ fontSize: 12, color: '#7b7b7b' }}>{b.label}</div>
            </div>
          ))}
        </div>
      ) : null}
    </Card>
  );

  return (
    <div style={{ display: 'grid', gap: 16 }}>
      <div style={{ display: 'flex', gap: 10 }}>
        <div style={{ flex: 1 }}>{topCard('#87a5ff', <SettingOutlined style={{ color: '#fff', fontSize: 17 }} />, '设备总量', 168, '台', [
          { value: 152, label: '在线设备', color: '#77cc48' },
          { value: 16, label: '离线设备', color: '#f50f38' },
        ])}</div>
        <div style={{ flex: 1.4 }}>{topCard('#ff6b72', <AreaChartOutlined style={{ color: '#fff', fontSize: 17 }} />, '今日销售额', '$ 12,345', '', [
          { value: '￥ 10,234', label: '昨日销售额', color: '#00a6ef' },
          { value: '￥ 72,120', label: '本周销售额', color: '#00a6ef' },
          { value: '￥ 301,220', label: '本月销售额', color: '#00a6ef' },
          { value: '￥ 20,987', label: '最大销售额', color: '#00a6ef' },
        ])}</div>
        <div style={{ flex: 1 }}>{topCard('#00d6af', <AlertOutlined style={{ color: '#fff', fontSize: 17 }} />, '待办事宜', 8, '项', [
          { value: 3, label: '今日警告数', color: '#d70010' },
          { value: 5, label: '缺货提醒', color: '#f59313' },
        ])}</div>
      </div>

      <div style={{ width: '100%', height: 50, backgroundColor: '#f3f3f3', border: '1px solid #e7e7e7', borderRadius: 3 }}>
        <div style={{ float: 'left', lineHeight: '50px', height: 50, marginLeft: 10, fontSize: 16 }}>使用在线率</div>
        <div style={{ float: 'right', lineHeight: '50px', height: 50, marginRight: 10, fontSize: 15 }}>
          <span onClick={() => setRangeType(1)} style={{ marginRight: 20, cursor: 'pointer', color: rangeType === 1 ? '#1890ff' : '#666' }}>一天</span>
          <span onClick={() => setRangeType(2)} style={{ marginRight: 20, cursor: 'pointer', color: rangeType === 2 ? '#1890ff' : '#666' }}>一周</span>
          <span onClick={() => setRangeType(3)} style={{ marginRight: 20, cursor: 'pointer', color: rangeType === 3 ? '#1890ff' : '#666' }}>一月</span>
          <span onClick={() => setRangeType(4)} style={{ marginRight: 15, cursor: 'pointer', color: rangeType === 4 ? '#1890ff' : '#666' }}>自选</span>
          <RangePicker style={{ width: 335 }} onFocus={() => setRangeType(4)} onChange={(v) => setDateRange(v)} />
          <Select
            value={metric}
            onChange={setMetric}
            size="middle"
            style={{ width: 200, marginLeft: 20 }}
            options={[
              { value: 'onlineRate', label: '在线率' },
              { value: 'sales', label: '销售额' },
              { value: 'alerts', label: '告警数' },
            ]}
          />
        </div>
      </div>

      <Card variant="borderless" styles={{ body: { padding: 0 } }}>
        <div ref={chartRef} style={{ height: 360, background: '#fff', border: '1px solid #e7e7e7', borderRadius: 4 }} />
      </Card>

      <Row gutter={[16, 16]}>
        <Col xs={24} md={12}>
          <Card title="今日统计" variant="borderless">
            <Row gutter={[16, 16]}>
              <Col span={12}><Statistic title="订单数" value={123} /></Col>
              <Col span={12}><Statistic title="销售额" value={12345} prefix="￥" /></Col>
              <Col span={12}><Statistic title="新增设备" value={4} /></Col>
              <Col span={12}><Statistic title="故障处理" value={7} /></Col>
            </Row>
          </Card>
        </Col>
        <Col xs={24} md={12}>
          <Card title="设备状态" variant="borderless">
            <Row gutter={[16, 16]}>
              <Col span={12}><Statistic title="在线设备" value={152} suffix="台" /></Col>
              <Col span={12}><Statistic title="离线设备" value={16} suffix="台" /></Col>
              <Col span={12}><Statistic title="低库存设备" value={12} suffix="台" /></Col>
              <Col span={12}><Statistic title="待维修设备" value={5} suffix="台" /></Col>
            </Row>
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        <Col xs={24}>
          <Card title="销售排名" variant="borderless" styles={{ body: { paddingTop: 8 } }}>
            <Tabs
              items={[
                {
                  key: 'machine',
                  label: '机器排名',
                  children: renderRankingTable(machineRanking),
                },
                {
                  key: 'user',
                  label: '用户排名',
                  children: renderRankingTable(userRanking),
                },
                {
                  key: 'product',
                  label: '产品排名',
                  children: renderRankingTable(productRanking),
                },
              ]}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
}

// 生成模拟数据
function generateSeries(rangeType, metric, dateRange) {
  // 生成 X 轴标签与对应数据
  let labels = [];
  let data = [];

  if (rangeType === 1) {
    // 一天：24 小时
    labels = Array.from({ length: 24 }, (_, i) => `${i}:00`);
  } else if (rangeType === 2) {
    // 一周：7 天
    labels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
  } else if (rangeType === 3) {
    // 一月：30 天
    labels = Array.from({ length: 30 }, (_, i) => `${i + 1}日`);
  } else {
    // 自选：按天展示，最多 30 天
    if (dateRange && dateRange.length === 2) {
      const start = dateRange[0];
      const end = dateRange[1];
      const days = Math.min(Math.max(end.diff(start, 'day') + 1, 1), 30);
      labels = Array.from({ length: days }, (_, i) => `第${i + 1}天`);
    } else {
      labels = Array.from({ length: 7 }, (_, i) => `第${i + 1}天`);
    }
  }

  // 根据指标生成数据曲线
  if (metric === 'onlineRate') {
    data = labels.map((_, i) => 70 + Math.round(20 * Math.sin(i / 3) + 10 * Math.random())); // 70%~100%
  } else if (metric === 'sales') {
    data = labels.map((_, i) => 500 + Math.round(400 * Math.sin(i / 2) + 300 * Math.random()));
  } else {
    // alerts
    data = labels.map((_, i) => Math.max(0, Math.round(10 * Math.sin(i / 2) + 6 * Math.random())));
  }

  return { labels, data };
}

// 删除了组件外的 useEffect，改为在组件内初始化与更新图表，避免作用域错误
